package com.abc.recycling.controller;

import com.abc.recycling.model.Order;
import com.abc.recycling.model.User;
import com.abc.recycling.model.request.CreateOrderRequest;
import com.abc.recycling.model.request.UpdateOrderRequest;
import com.abc.recycling.service.OrderService;
import com.abc.recycling.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api/orders")
@RequiredArgsConstructor
public class OrderApiController {

    private final OrderService orderService;
    private final UserService userService;

    @PostMapping("/create")
    public Order createOrder(@RequestBody Order order, Authentication authentication) {
        Long userId = userService.getUserByUsername(authentication.getName()).getId();
        order.setUserId(userId);
        return orderService.createOrder(order);
    }

    @GetMapping("/{id}")
    public Order getOrder(@PathVariable Long id) {
        return orderService.getOrderById(id);
    }

    @PostMapping("/{id}/accept")
    public ResponseEntity<?> acceptOrder(@PathVariable Long id, Authentication authentication) {
        try {
            User collector = userService.getUserByUsername(authentication.getName());
            Order order = orderService.getOrderById(id);
            
            if (order == null) {
                return ResponseEntity.notFound().build();
            }
            
            if (!order.getStatus().equals("PENDING")) {
                return ResponseEntity.badRequest().body("订单状态不正确");
            }
            
            order.setCollectorId(collector.getId());
            order.setStatus("PROCESSING");
            order.setUpdateTime(LocalDateTime.now());
            orderService.updateOrder(order);
            
            return ResponseEntity.ok().build();
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    @GetMapping("/my")
    public Page<Order> getMyOrders(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "5") int size,
            Authentication authentication) {
        Long userId = userService.getUserByUsername(authentication.getName()).getId();
        PageRequest pageRequest = PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "createTime"));
        return orderService.getOrdersByUserIdPaged(userId, pageRequest);
    }

    @PostMapping("/{id}/complete")
    public ResponseEntity<?> completeOrder(
            @PathVariable Long id,
            @RequestParam Double actualWeight,
            @RequestParam Double price,
            Authentication authentication) {
        try {
            User collector = userService.getUserByUsername(authentication.getName());
            Order order = orderService.getOrderById(id);
            
            if (order == null) {
                return ResponseEntity.notFound().build();
            }
            
            if (!order.getStatus().equals("PROCESSING") || !collector.getId().equals(order.getCollectorId())) {
                return ResponseEntity.badRequest().body("订单状态不正确或无权操作");
            }
            
            order.setActualWeight(actualWeight);
            order.setPrice(new BigDecimal(price.toString()));
            order.setStatus("COMPLETED");
            order.setCompleteTime(LocalDateTime.now());
            order.setUpdateTime(LocalDateTime.now());
            orderService.updateOrder(order);
            
            return ResponseEntity.ok().build();
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    /**
     * 获取订单详情
     */
    @GetMapping("/{orderId}")
    public ResponseEntity<?> getOrderDetail(@PathVariable Long orderId, Authentication authentication) {
        try {
            User collector = userService.getUserByUsername(authentication.getName());
            Order order = orderService.getOrderById(orderId);
            
            if (order == null) {
                return ResponseEntity.notFound().build();
            }
            
            // 只能查看自己的订单
            if (collector.getId().equals(order.getCollectorId())) {
                return ResponseEntity.ok(order);
            } else {
                return ResponseEntity.badRequest().body("无权查看此订单");
            }
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    @PutMapping("/{id}/status")
    public ResponseEntity<Order> updateOrderStatus(@PathVariable Long id, @RequestParam String status) {
        Order order = orderService.getOrderById(id);
        if (order != null) {
            order.setStatus(status);
            order.setUpdateTime(LocalDateTime.now());
            return ResponseEntity.ok(orderService.updateOrder(order));
        }
        return ResponseEntity.notFound().build();
    }

    @PutMapping("/{id}/complete")
    public ResponseEntity<Order> completeOrder(@PathVariable Long id, 
            @RequestParam Double actualWeight,
            @RequestParam Double price) {
        Order order = orderService.getOrderById(id);
        if (order != null) {
            order.setStatus("COMPLETED");
            order.setActualWeight(actualWeight);
            order.setPrice(new BigDecimal(price.toString()));
            order.setCompleteTime(LocalDateTime.now());
            order.setUpdateTime(LocalDateTime.now());
            return ResponseEntity.ok(orderService.updateOrder(order));
        }
        return ResponseEntity.notFound().build();
    }

    @PostMapping
    public ResponseEntity<?> createOrder(@RequestBody CreateOrderRequest request) {
        try {
            Order order = new Order();
            order.setUserId(request.getUserId());
            order.setCollectorId(request.getCollectorId());
            order.setStatus(request.getStatus());
            order.setTotalAmount(new BigDecimal(request.getTotalAmount().toString()));
            order.setAddress(request.getAddress());
            order.setContactPhone(request.getContactPhone());
            order.setDescription(request.getDescription());
            order.setCreateTime(LocalDateTime.now());
            order.setUpdateTime(LocalDateTime.now());
            
            Order savedOrder = orderService.createOrder(order);
            return ResponseEntity.ok(savedOrder);
        } catch (Exception e) {
            log.error("创建订单失败", e);
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }
    
    @PutMapping("/{orderId}")
    public ResponseEntity<?> updateOrder(@PathVariable Long orderId, @RequestBody UpdateOrderRequest request) {
        try {
            Order order = orderService.getOrderById(orderId);
            if (order == null) {
                return ResponseEntity.notFound().build();
            }
            
            order.setStatus(request.getStatus());
            order.setTotalAmount(new BigDecimal(request.getTotalAmount().toString()));
            order.setAddress(request.getAddress());
            order.setContactPhone(request.getContactPhone());
            order.setDescription(request.getDescription());
            order.setUpdateTime(LocalDateTime.now());
            
            Order updatedOrder = orderService.updateOrder(order);
            return ResponseEntity.ok(updatedOrder);
        } catch (Exception e) {
            log.error("更新订单失败", e);
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }
} 